//    Copyright (C) Kherty.  All rights reserved.
#region

using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reflection;
using OpenLS.Core.Serialization;

#endregion

namespace OpenLS.Spreadsheet
{
    internal class ExternalDefinedName : IOfficeXmlSerializable, INotifyPropertyChanged
    {
        private const string xmlName = "definedName";
        private string _name;
        private string _refersTo; //\\todo: get object
        private int? _sheetId; //\\todo get worksheet

        public string Name
        {
            get { return _name; }
            set { _name = value;notifyPropertyChanged("Name"); }
        }

        #region IOfficeXmlSerializable Members

        public void ReadXml(ReadContext context)
        {
            using (var c = context.Read(xmlName))
            {
                Name = c.GetString("name");
                _refersTo = c.GetOptionalString("refersTo");
                _sheetId = c.GetOptionalUIntegerAsInteger("sheetId");
            }
        }

        public void WriteXml(WriteContext context)
        {
            using (var c = context.Write(xmlName))
            {
                c.SetString("name", Name);
                c.SetOptionalString("refersTo", _refersTo);
                c.SetOptionalUIntegerAsInteger("sheetId", _sheetId);
            }
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        private void notifyPropertyChanged(string propertyName)
        {
            Contract.Requires(GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null);
            PropertyChangedEventHandler changed = PropertyChanged;
            if (changed != null) changed(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}